<?php if (!defined('BASEPATH')) exit('No direct script access allowed');
/**
 * Created by CodeTlan.
 * User: Ing. Miguel Salas
 * Date: 3/4/12
 * Time: 4:07 PM
 */
class Logins extends CI_Controller
{
    function __construct(){
        parent::__construct();
        $this->load->model("user", "dao");
    }
    function index(){

        if(!$this->session->isLogged()){
            $this->load->view('login');
        }
        else{
            $this->load->view('logged');
        }
    }

    function login(){
        $user=$this->input->post("u");
        $password=$this->input->post("p");

        $data=array(
            "U.usuario_k"=>$user,
            "U.password"=>md5($password)
        );

        $userData = $this->dao->find('U.usuario_k, U.rol_k, U.activo, U.logins, U.last_login',$data,0,1);
        if ($userData["total"]==0){
            echo '{"success":false,"error":"El login o la contraseña no son correctas. Inténtelo de nuevo."}';
            return false;
        }
        else{
            if($userData["data"][0]->activo==0){
                echo '{"success":false,"error":"Su cuenta ha sido desactivada, contacte al administrador."}';
                return false;
            }
        }

        if($this->_logs($userData["data"][0])){

            $this->session->login($userData["data"][0]);
            echo "{success:true}";
        }
    }

    function _logs($userData){
        $data=array(
            'logins' => $userData->logins+1,
            'last_login' => date("Y-m-d")
        );
        return $this->dao->edit($data,array('usuario_k' => $userData->usuario_k));
    }
}
